import config from "@/config/index.js";
const baseUrl = config.baseUrl;
/**
 * 请求数据封装方法
 * @param method 请求方式 GET POST PUT
 * @param url 请求地址（login/login）
 * @param data 请求对象
 * @param loading 是否展示loading
 * @param loadingTitle 展示loading文字
 * @returns {Promise<unknown>}
 */
function fetch(method, url, data, loading, loadingTitle, paramsUrl) {
	return new Promise((resolve, reject) => {
		//显示加载动画
		// if (loading) {
		// 	uni.showLoading({
		// 		title: loadingTitle,
		// 		mask: true,
		// 	});
		// }
		const params = {};
		//获取jwt
		// console.log(uni.getStorageSync("token"), " .........")
		let token = uni.getStorageSync("token") ?
			uni.getStorageSync("token") :
			"";
		//添加token
		Object.assign(params, data);
		// Object.assign(params, obj);
		// console.log(params);
		//发起请求
		if (method == 'POST') {
			Object.assign(params);
			url = `${url}`
		} else {
			Object.assign(params);
		}
		uni.request({
			url,
			method,
			data: params,
			header: {
				// 数据被编码为名称/值对
				"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
				'authoriztion': `${token}`
			},
			success: res => {
				let message = res.data.msg || '';
				let codes = Number(res.data.code);
				// console.log(codes)
				if (codes == 200) {
					resolve(res.data);
				} else if (codes == 501) {
					uni.showToast({
						title: '当前门诊不存在',
						duration: 2000,
						icon: 'none',
						mask: true
					});
				} else {
					if (message) {
						uni.showToast({
							title: `${message}`,
							duration: 2000,
							icon: 'none',
							mask: true
						});
					} else {
						uni.showToast({
							title: `网络连接超时`,
							duration: 2000,
							icon: 'none',
						});
					}
					resolve(res.data);
				}
			},
			fail: err => {
				reject(err);
			},
			complete: () => {
				setTimeout(function() {
					uni.stopPullDownRefresh(); //停止下拉刷新动画
				}, 1000);
			},
		});
	});
}
export default {
	get(url, params, loading, loadingTitle, obs) {
		return fetch("GET", baseUrl + url, params, loading, loadingTitle, url);
	},
	post(url, params, loading, loadingTitle) {
		return fetch("POST", baseUrl + url, params, loading, loadingTitle, url);
	},
	put(url, params, loading, loadingTitle) {
		return fetch("PUT", baseUrl + url, params, loading, loadingTitle, url);
	},
};
